<template>
  <div class="factor-tree-container">
    <div class="main-content">
      <!-- 左侧树列表 -->
      <div class="tree-list-panel">
        <div class="panel-header">
          <h3>因子树列表</h3>
        </div>
        <div class="tree-list">
          <div
              v-for="tree in treeList"
              :key="tree.id"
              class="tree-item"
              :class="{ active: currentTree.id === tree.id }"
              @click="selectTree(tree)"
          >
            <div class="tree-info">
              <div class="tree-name">{{ tree.treeName }}</div>
              <div class="tree-desc">{{ tree.description }}</div>
            </div>
            <div class="tree-status">
              <el-tag :type="tree.enabled ? 'success' : 'info'" size="small">
                {{ tree.enabled ? '启用' : '禁用' }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间可视化区域 -->
      <div class="visualization-panel">
        <div class="panel-header">
          <h3>因子树可视化</h3>
          <div class="tree-actions">
            <el-button type="primary" plain @click="saveTree" :loading="saving">
              <el-icon><Star/></el-icon>
              保存树结构
            </el-button>
            <el-button type="primary" plain  @click="exportTree">
              <el-icon><Upload /></el-icon>
              导出JSON</el-button>
            <el-button type="primary" plain @click="createNewTree">
              <el-icon><Plus /></el-icon>
              新建因子树
            </el-button>
          </div>
        </div>
        <div class="tree-visualization" ref="treeContainer">
          <div v-if="currentTree.rootNode" class="tree-root">
            <TreeNode
                :node="currentTree.rootNode"
                :selected-node="selectedNode"
                @select="selectNode"
                @update="updateNodeData"
                @delete="deleteNode"
                @add-child="addChildNode"
                @drag-start="onDragStart"
                @drop="onDrop"
            />
          </div>
          <div v-else class="empty-tree">
            <el-empty description="请选择或创建因子树">
              <el-button type="primary" @click="addRootNode">添加节点</el-button>
            </el-empty>
          </div>
        </div>
      </div>

      <!-- 右侧节点配置 -->
      <div class="node-config-panel">
        <div class="panel-header">
          <h3>节点配置</h3>
        </div>
        <div v-if="selectedNode" class="node-config">
          <el-form :model="selectedNode" label-width="80px">
            <el-form-item label="节点名称">
              <el-input v-model="selectedNode.nodeName" placeholder="输入节点名称"></el-input>
            </el-form-item>

            <el-form-item label="节点类型">
              <el-select v-model="selectedNode.nodeType" placeholder="选择节点类型" @change="onNodeTypeChange">
                <el-option label="基础因子" value="BASIC"></el-option>
                <el-option label="衍生因子" value="DERIVED"></el-option>
                <el-option label="风格因子" value="STYLE"></el-option>
                <el-option label="组合节点" value="COMBINATION"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="因子代码" v-if="selectedNode.nodeType !== 'COMBINATION'">
              <el-select
                  v-model="selectedNode.factorCode"
                  placeholder="选择因子"
                  filterable
                  allow-create
                  @change="val => console.log('选中因子:', val)"
              >
                <el-option
                    v-for="factor in getCurrentFactorList"
                    :key="factor.factorCode || factor.code"
                    :label="factor.factorName || factor.name"
                    :value="factor.factorCode || factor.code"
                ></el-option>
              </el-select>
              <div v-if="getCurrentFactorList.length === 0" style="color: #999; font-size: 12px; margin-top: 4px;">无可选因子，请检查节点类型或数据</div>
            </el-form-item>

            <el-form-item label="权重" v-if="selectedNode.nodeType === 'COMBINATION'">
              <el-input-number
                  v-model="selectedNode.weight"
                  :min="0"
                  :max="1"
                  :precision="3"
                  :step="0.1"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="描述">
              <el-input
                  v-model="selectedNode.description"
                  type="textarea"
                  placeholder="输入节点描述"
                  :rows="2"
              ></el-input>
            </el-form-item>
          </el-form>

          <div class="node-actions">
            <el-button type="primary" @click="updateNode">更新节点</el-button>
            <el-button @click="clearSelection">取消选择</el-button>
          </div>
        </div>
        <div v-else class="no-selection">
          <el-empty description="请选择一个节点进行配置"></el-empty>
        </div>
      </div>
    </div>

    <el-dialog
        v-model="treeDialogVisible"
        :title="editingTree.id ? '编辑因子树' : '新建因子树'"
        width="500px"
    >
      <el-form :model="editingTree" label-width="100px">
        <el-form-item label="树名称" required>
          <el-input v-model="editingTree.treeName" placeholder="输入因子树名称"></el-input>
        </el-form-item>
        <el-form-item label="业务场景" required>
          <el-select v-model="editingTree.businessScenario" placeholder="选择业务场景">
            <el-option label="选基" value="FUND_SELECTION"></el-option>
            <el-option label="量化投研" value="QUANT_RESEARCH"></el-option>
            <el-option label="特色数据" value="SPECIAL_DATA"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
              v-model="editingTree.description"
              type="textarea"
              placeholder="输入因子树描述"
              :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="editingTree.enabled"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="treeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveTreeInfo">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="factorsDialogVisible" title="因子计算结果" width="600px">
      <el-table :data="factors" border style="width: 100%">
        <el-table-column prop="name" label="因子名称" />
        <el-table-column prop="type" label="类型" />
        <el-table-column prop="value" label="值" />
      </el-table>
      <template #footer>
        <el-button @click="factorsDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus ,Upload,Star} from '@element-plus/icons-vue'
import TreeNode from './TreeNode.vue'
import axios from 'axios'

export default {
  name: 'FactorTree',
  components: {
    TreeNode,
    Plus,
    Upload,
    Star
  },
  setup() {
    const treeList = ref([]);
    const currentTree = ref({});
    const selectedNode = ref(null);
    const saving = ref(false);
    const treeDialogVisible = ref(false);
    const editingTree = ref({});
    let draggingNode = null;
    let draggingParent = null;

    // 固定基础因子列表
    const basicFactors = ref([
      { id: 1, factorCode: 'simple_return', factorName: '简单收益率因子' },
      { id: 2, factorCode: 'annual_return', factorName: '年化收益率因子' },
      { id: 3, factorCode: 'relative_return', factorName: '对数收益率因子' },
      { id: 4, factorCode: 'volatility', factorName: '波动率因子' },
      { id: 5, factorCode: 'sharpe_ratio', factorName: '夏普比率因子' },
      { id: 6, factorCode: 'max_drawdown', factorName: '最大回撤因子' },
      { id: 7, factorCode: 'downside_risk', factorName: '下行风险因子' },
      { id: 8, factorCode: 'relative_strength', factorName: '相对强弱指数因子' },
      { id: 9, factorCode: 'moving_average', factorName: '移动平均值因子' },
      { id: 10, factorCode: 'subscription_freq', factorName: '申购开放频率因子' },
      { id: 11, factorCode: 'redemption_freq', factorName: '赎回开放频率因子' }
    ]);
    const derivedFactors = ref([]);
    const styleFactors = ref([]);

    const loadAllFactors = async () => {
      try {
        const [derivedRes, styleRes] = await Promise.all([
          axios.get('http://localhost:8080/derived-factor/noPage'),
          axios.get('http://localhost:8080/style-factor/noPage')
        ]);
        derivedFactors.value = derivedRes.data || [];
        styleFactors.value = styleRes.data || [];
      } catch (error) {
        console.error('加载因子列表失败', error);
      }
    };

    const getCurrentFactorList = computed(() => {
      if (selectedNode.value?.nodeType === 'BASIC') {
        console.log('基础因子列表:', basicFactors.value);
        return basicFactors.value;
      }
      if (selectedNode.value?.nodeType === 'DERIVED') {
        console.log('衍生因子列表:', derivedFactors.value);
        return derivedFactors.value;
      }
      if (selectedNode.value?.nodeType === 'STYLE') {
        console.log('风格因子列表:', styleFactors.value);
        return styleFactors.value;
      }
      return [];
    });

    // 递归组装树结构
    function buildTreeFromNodes(nodes) {
      if (!nodes || nodes.length === 0) return [];
      const nodeMap = {};
      nodes.forEach(n => {
        nodeMap[String(n.id)] = { ...n, children: [] };
      });
      const roots = [];
      nodes.forEach(n => {
        const parentId = n.parentId;
        // 兼容 null, undefined, "null", 0, "0"
        if (parentId === null || parentId === undefined || parentId === "null" || parentId === 0 || parentId === "0") {
          roots.push(nodeMap[String(n.id)]);
        } else if (nodeMap[String(parentId)]) {
          nodeMap[String(parentId)].children.push(nodeMap[String(n.id)]);
        }
      });
      return roots.length === 1 ? roots[0] : roots;
    }

    // 加载因子树列表
    const loadTreeList = async () => {
      try {
        const res = await axios.get('http://localhost:8080/factor-tree');
        treeList.value = res.data;
        console.log(res.data);
        if (treeList.value.length > 0) {
          await selectTree(treeList.value[0]);
        }
      } catch (error) {
        ElMessage.error('加载因子树列表失败');
      }
    }
    // 选中因子树加载结构
    const selectTree = async (tree) => {
      currentTree.value = tree;
      try {
        const res = await axios.get(`http://localhost:8080/factor-tree/${tree.id}/structure`);
        // 判断是否已是树形结构
        if (Array.isArray(res.data) && res.data.length > 0 && res.data[0].children) {
          currentTree.value.rootNode = res.data[0];
        } else {
          currentTree.value.rootNode = buildTreeFromNodes(res.data);
        }
        selectedNode.value = null;
      } catch (error) {
        ElMessage.error('加载因子树结构失败');
      }
    }
    // 新建因子树
    const createNewTree = () => {
      editingTree.value = {
        id: null,
        treeName: '',
        description: '',
        enabled: true,
        businessScenario: '',
        sortOrder: 0
      }
      treeDialogVisible.value = true
    }
    // 保存因子树信息（新建/编辑）
    const saveTreeInfo = async () => {
      if (!editingTree.value.treeName || !editingTree.value.businessScenario) {
        ElMessage.warning('请输入因子树名称和业务场景')
        return
      }
      try {
        let res;
        if (editingTree.value.id) {
          res = await axios.put(`http://localhost:8080/factor-tree/${editingTree.value.id}`, editingTree.value);
        } else {
          res = await axios.post('http://localhost:8080/factor-tree', editingTree.value);
        }
        treeDialogVisible.value = false;
        await loadTreeList();
        // 选中新建的树，保证currentTree.value.id为最新id
        if (res && res.data && res.data.id) {
          const newTree = treeList.value.find(t => t.id === res.data.id);
          if (newTree) await selectTree(newTree);
        }
        ElMessage.success('保存成功');
      } catch (error) {
        ElMessage.error('保存失败');
        console.error(error);
      }
    }

    const selectNode = (node) => {
      selectedNode.value = { ...node }
    }

    const clearSelection = () => {
      selectedNode.value = null
    }

    // 构造后端需要的节点payload
    function buildNodePayload(node, parentId, treeId) {
      const payload = {
        id: node.id,
        nodeName: node.nodeName || node.name || '',
        nodeType: node.nodeType || node.type || 'BASIC',
        parentId: parentId === undefined ? null : parentId,
        factorTree: { id: treeId },
        sortOrder: typeof node.sortOrder === 'number' ? node.sortOrder : 0,
        level: typeof node.level === 'number' ? node.level : 0,
        path: node.path || '',
        enabled: node.enabled !== undefined ? !!node.enabled : true,
        description: node.description || '',
        createdBy: node.createdBy || undefined,
        updatedBy: node.updatedBy || undefined
      };
      
      // 只有当factor存在且有效时才添加
      if (node.factor && node.factor.id && node.factor.id > 0) {
        payload.factor = { id: node.factor.id };
      }
      
      // 移除undefined的字段
      Object.keys(payload).forEach(key => payload[key] === undefined && delete payload[key]);
      return payload;
    }

    const updateNode = async () => {
      if (!selectedNode.value) return;
      if (!selectedNode.value.id || typeof selectedNode.value.id !== 'number' || String(selectedNode.value.id).length > 12) {
        ElMessage.error('请先保存树结构，再编辑节点');
        return;
      }
      const payload = buildNodePayload(selectedNode.value, selectedNode.value.parentId, currentTree.value.id);
      console.log('请求payload:', payload);
      try {
        const res = await axios.put(`http://localhost:8080/factor-tree/node/${selectedNode.value.id}`, payload);
        console.log('后端返回:', res.data);
        await selectTree(currentTree.value); // 强制刷新树结构
        ElMessage.success('节点更新成功');
      } catch (error) {
        ElMessage.error('节点更新失败: ' + (error.response?.data?.message || error.message));
        console.error(error);
      }
    }

    const updateNodeData = (nodeData) => {
      // 递归更新节点
      const updateNodeRecursive = (node) => {
        if (node.id === nodeData.id) {
          Object.assign(node, nodeData)
          return true
        }
        if (node.children) {
          for (const child of node.children) {
            if (updateNodeRecursive(child)) {
              return true
            }
          }
        }
        return false
      }

      if (currentTree.value.rootNode) {
        updateNodeRecursive(currentTree.value.rootNode)
      }
    }

    const addChildNode = async (parentNode) => {
      const nodeType = 'BASIC';
      const factorList = basicFactors.value;
      const firstFactor = factorList.length > 0 ? factorList[0] : null;
      const parentId = Number(parentNode.id);
      const treeId = Number(currentTree.value.id);
      const factorId = Number(firstFactor ? firstFactor.id : 0);

      if (!parentId || !treeId) {
        ElMessage.error('父节点ID或树ID无效');
        return;
      }

      const payload = {
        nodeName: "新节点",
        nodeType: nodeType,
        parentId: parentId,
        factorTree: { id: treeId },
        enabled: true,
        sortOrder: 0,
        level: 0,
        description: ""
      };

      // 只有当因子ID有效时才添加factor字段
      if (factorId && factorId > 0) {
        payload.factor = { id: factorId };
      }

      console.log('新增节点payload:', payload);

      try {
        await axios.post(
            'http://localhost:8080/factor-tree/node',
            payload,
            { headers: { 'Content-Type': 'application/json' } }
        );
        await selectTree(currentTree.value);
        ElMessage.success('已添加子节点并自动保存');
      } catch (error) {
        ElMessage.error('添加子节点失败: ' + (error.response?.data?.message || error.message));
        console.error('状态码:', error.response?.status);
        console.error('错误信息:', error.response?.data);
        console.error('请求头:', error.response?.headers);
      }
    };
    // 删除节点（直接调后端接口）
    const deleteNode = async (node) => {
      try {
        await ElMessageBox.confirm('确定要删除这个节点吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        if (!node.id) {
          ElMessage.error('节点ID无效，无法删除');
          return;
        }
        await axios.delete(`http://localhost:8080/factor-tree/node/${node.id}`);
        // 本地树移除节点
        function deleteNodeRecursive(parent, nodeToDelete) {
          if (!Array.isArray(parent.children)) parent.children = [];
          const idx = parent.children.findIndex(child => child === nodeToDelete || child.id === nodeToDelete.id);
          if (idx !== -1) {
            parent.children.splice(idx, 1);
            parent.children = [...parent.children];
            return true;
          }
          for (const child of parent.children) {
            if (deleteNodeRecursive(child, nodeToDelete)) return true;
          }
          return false;
        }
        let deleted = false;
        if (currentTree.value.rootNode) {
          if (currentTree.value.rootNode === node || currentTree.value.rootNode.id === node.id) {
            currentTree.value.rootNode = null;
            deleted = true;
          } else {
            deleted = deleteNodeRecursive(currentTree.value.rootNode, node);
          }
        }
        if (deleted) {
          if (selectedNode.value && (selectedNode.value === node || selectedNode.value.id === node.id)) {
            selectedNode.value = null;
          }
          ElMessage.success('删除节点并自动保存');
        } else {
          ElMessage.error('未找到要删除的节点');
        }
      } catch (error) {
        ElMessage.error('删除节点失败: ' + (error.response?.data?.message || error.message));
      }
    };

    // 保存前校验
    function validateTree(node) {
      if (!node) return false;
      if (!Array.isArray(node.children)) node.children = [];
      for (const child of node.children) {
        if (!validateTree(child)) return false;
      }
      return true;
    }

    const onNodeTypeChange = () => {
      if (selectedNode.value) {
        // 根据节点类型重置相关字段
        if (selectedNode.value.nodeType === 'COMBINATION') {
          selectedNode.value.factorCode = null
        } else {
          selectedNode.value.weight = null
        }
      }
    }

    // 递归清理所有临时id，全部设为null
    function clearTempIds(node) {
      if (node.id && (typeof node.id !== 'number' || String(node.id).length > 12)) {
        node.id = null;
      }
      if (Array.isArray(node.children)) {
        node.children.forEach(child => clearTempIds(child));
      }
    }

    const saveTree = async () => {
      if (!currentTree.value.rootNode) {
        ElMessage.warning('请先创建因子树结构');
        return;
      }
      if (!validateTree(currentTree.value.rootNode)) {
        ElMessage.error('树结构有误，请检查所有节点');
        return;
      }
      saving.value = true;
      try {
        clearTempIds(currentTree.value.rootNode);
        await saveNodeRecursive(currentTree.value.rootNode, null, currentTree.value.id);
        console.log(1)
        await selectTree(currentTree.value);
        console.log(2)
        ElMessage.success('保存成功');
      } catch (error) {
        ElMessage.error('保存失败: ' + (error.response?.data?.message || error.message));
        console.error('保存失败:', error);
      } finally {
        saving.value = false;
      }
    }

    const saveNodeRecursive = async (node, parentId, treeId) => {
      if (!node || typeof node !== 'object') return;
      if (!Array.isArray(node.children)) node.children = [];
      const realTreeId = treeId || (currentTree.value && currentTree.value.id);
      if (!realTreeId) {
        throw new Error('树ID无效，无法保存节点');
      }
      const payload = buildNodePayload(node, parentId, realTreeId);
      console.log('保存节点payload:', payload);
      let nodeId = node.id;
      try {
        if (!nodeId || typeof nodeId !== 'number' || String(nodeId).length > 12) {
          const res = await axios.post('http://localhost:8080/factor-tree/node', payload);
          console.log('创建节点返回:', res.data);
          nodeId = res.data.id;
          node.id = nodeId;
          if (Array.isArray(node.children)) {
            node.children.forEach(child => { child.parentId = nodeId; });
          }
        } else {
          const res = await axios.put(`http://localhost:8080/factor-tree/node/${nodeId}`, payload);
          console.log('更新节点返回:', res.data);
        }
        if (Array.isArray(node.children) && node.children.length > 0) {
          const sortedChildren = [...node.children].sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0));
          for (const child of sortedChildren) {
            await saveNodeRecursive(child, nodeId, realTreeId);
          }
        }
      } catch (error) {
        console.error('节点保存失败:', error);
        throw error;
      }
    }

    const exportTree = () => {
      if (!currentTree.value.rootNode) {
        ElMessage.warning('没有可导出的因子树')
        return
      }
      const dataStr = JSON.stringify(currentTree.value, null, 2)
      const dataBlob = new Blob([dataStr], { type: 'application/json' })
      const url = URL.createObjectURL(dataBlob)
      const link = document.createElement('a')
      link.href = url
      link.download = `${currentTree.value.treeName}.json`
      link.click()
      URL.revokeObjectURL(url)
      ElMessage.success('导出成功')
    }
    const onDragStart = ({ node, parent }) => {
      console.log('FactorTree: onDragStart 被调用', {
        nodeName: node?.nodeName,
        nodeId: node?.id,
        parentName: parent?.nodeName,
        parentId: parent?.id,
        fullNode: node,
        fullParent: parent
      });
      draggingNode = node;
      draggingParent = parent;
      console.log('FactorTree: 设置拖拽状态', {
        draggingNodeName: draggingNode?.nodeName,
        draggingParentName: draggingParent?.nodeName,
        draggingNodeId: draggingNode?.id,
        draggingParentId: draggingParent?.id
      });
    };

    const onDrop = async ({ node: targetNode, parent: targetParent }) => {
      console.log('FactorTree: onDrop 被调用', {
        targetNodeName: targetNode?.nodeName,
        targetParentName: targetParent?.nodeName,
        draggingNodeName: draggingNode?.nodeName,
        draggingParentName: draggingParent?.nodeName,
        draggingParentId: draggingParent?.id,
        targetParentId: targetParent?.id,
        isSameParent: draggingParent?.id === targetParent?.id,
        fullTargetNode: targetNode,
        fullDraggingNode: draggingNode,
        fullTargetParent: targetParent,
        fullDraggingParent: draggingParent
      });

      if (draggingNode && targetNode && draggingNode !== targetNode) {
        // 检查是否为根节点交换（两个节点都没有父节点）
        const isRootNodeSwap = !draggingParent && !targetParent;
        // 检查是否为根节点拖拽到子节点位置
        const isRootToChild = !draggingParent && targetParent;

        console.log('拖拽类型判断:', { isRootNodeSwap, isRootToChild, draggingParentId: draggingParent?.id, targetParentId: targetParent?.id });

        if (isRootNodeSwap) {
          console.log('根节点之间交换');
          // 根节点之间交换
          const rootNodes = currentTree.value.rootNode.children || [];
          const fromIdx = rootNodes.findIndex(child => child.id === draggingNode.id);
          const toIdx = rootNodes.findIndex(child => child.id === targetNode.id);
          console.log('根节点交换索引:', {
            fromIdx,
            toIdx,
            rootNodesCount: rootNodes.length,
            draggingNodeId: draggingNode.id,
            targetNodeId: targetNode.id,
            rootNodeIds: rootNodes.map(n => n.id)
          });

          if (fromIdx > -1 && toIdx > -1) {
            const [dragged] = rootNodes.splice(fromIdx, 1);
            rootNodes.splice(toIdx, 0, dragged);
            currentTree.value.rootNode.children = rootNodes.slice();

            // 更新sortOrder以保持顺序
            rootNodes.forEach((node, index) => {
              node.sortOrder = index;
            });

            console.log('根节点交换成功，新顺序:', rootNodes.map(n => n.id));
            ElMessage.success('根节点交换成功，正在保存...');
            // 自动保存
            try {
              await saveTree();
            } catch (error) {
              ElMessage.error('保存失败: ' + error.message);
            }
          } else {
            console.log('根节点索引查找失败:', { fromIdx, toIdx });
            ElMessage.error('根节点交换失败');
          }
        } else if (isRootToChild) {
          console.log('根节点拖拽到子节点位置，不支持此操作');
          ElMessage.warning('不支持将根节点拖拽到子节点位置');
        } else if (draggingParent && targetParent && draggingParent.id === targetParent.id) {
          console.log('同父节点交换，开始处理...');
          // 同父节点下交换
          const siblings = draggingParent.children;
          const fromIdx = siblings.findIndex(child => child.id === draggingNode.id);
          const toIdx = siblings.findIndex(child => child.id === targetNode.id);
          console.log('交换索引:', { fromIdx, toIdx, siblingsCount: siblings.length });

          if (fromIdx > -1 && toIdx > -1) {
            const [dragged] = siblings.splice(fromIdx, 1);
            siblings.splice(toIdx, 0, dragged);
            draggingParent.children = siblings.slice();

            // 更新sortOrder以保持顺序
            siblings.forEach((node, index) => {
              node.sortOrder = index;
            });

            console.log('交换成功，新顺序:', siblings.map(n => n.nodeName));
            ElMessage.success('节点交换成功，正在保存...');
            // 自动保存
            try {
              await saveTree();
            } catch (error) {
              ElMessage.error('保存失败: ' + error.message);
            }
          } else {
            console.log('索引查找失败:', { fromIdx, toIdx });
            ElMessage.error('交换失败：找不到节点位置');
          }
        } else {
          console.log('不同父节点，无法交换');
          ElMessage.warning('只支持同一父节点下的节点交换');
        }
        draggingNode = null;
        draggingParent = null;
      } else {
        console.log('拖拽条件不满足:', {
          hasDraggingNode: !!draggingNode,
          hasTargetNode: !!targetNode,
          notSameNode: draggingNode !== targetNode
        });
      }
    };
    function findParent(root, child) {
      if (!root.children) return null;
      for (let c of root.children) {
        if (c === child) return root;
        const res = findParent(c, child);
        if (res) return res;
      }
      return null;
    }
    const addRootNode = () => {
      currentTree.value.rootNode = {
        id: null,
        nodeName: '新根节点',
        nodeType: 'BASIC',
        parentId: null,
        enabled: true,
        sortOrder: 0,
        level: 0,
        description: '',
        children: []
      };
      ElMessage.success('已添加根节点，请在右侧配置');
    };
    onMounted(() => {
      loadAllFactors();
      loadTreeList();
    })

    return {
      treeList,
      currentTree,
      selectedNode,
      saving,
      treeDialogVisible,
      editingTree,
      basicFactors,
      derivedFactors,
      styleFactors,
      loadAllFactors,
      getCurrentFactorList,
      selectTree,
      createNewTree,
      saveTreeInfo,
      selectNode,
      clearSelection,
      updateNode,
      updateNodeData,
      deleteNode,
      onNodeTypeChange,
      saveTree,
      exportTree,
      onDragStart,
      onDrop,
      addRootNode,
      addChildNode
    }
  }
}
</script>

<style scoped>
.factor-tree-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.54) 0%, rgba(118, 75, 162, 0) 100%);
  color: rgba(51, 51, 51, 0.69);
  overflow: hidden; /* 防止整体滚动 */
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
}

.header h2 {
  margin: 0;
  color: rgba(44, 62, 80, 0.6);
  font-weight: 600;
}

.main-content {
  flex: 1;
  display: grid;
  grid-template-columns: 320px 1fr 360px;
  gap: 20px;
  padding: 20px;
  overflow: hidden;
}
.tree-list-panel,
.visualization-panel,
.node-config-panel {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.panel-header {
  display: flex;
  align-items: center;   /* 垂直居中 */
  justify-content: space-between; /* 左右撑开 */
  gap: 16px;             /* 标题和按钮之间的安全距离 */
  padding: 12px 16px;
  background: #fafafa;
  background: linear-gradient(135deg, rgba(157, 147, 251, 0.47) 0%, #57b8f5 100%);
  border-bottom: 1px solid #e4e7ed;
}

.panel-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: rgba(48, 50, 51, 0.76);
}

.tree-actions {
  display: flex;
  gap: 8px;              /* 两个按钮之间的间距 */
  align-items: center;
}
.tree-list {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.tree-item {
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.8);
  border: 2px solid transparent;
  cursor: pointer;
  transition: all 0.3s ease;
}

.tree-item:hover {
  background: rgba(255, 255, 255, 0.95);
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.tree-item.active {
  border-color: #409eff;
  background: rgba(64, 158, 255, 0.1);
}

.tree-name {
  font-weight: 600;
  margin-bottom: 5px;
  color: #2c3e50;
}

.tree-desc {
  font-size: 12px;
  color: #666;
  margin-bottom: 10px;
}

.tree-visualization {
  flex: 1;
  padding: 20px;
  overflow: auto;
  background: linear-gradient(135deg, rgba(168, 198, 237, 0.63) 0%, rgba(254, 214, 227, 0.13) 100%);
}

.tree-root {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.empty-tree {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.node-config {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.no-selection {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.node-actions {
  margin-top: 20px;
  display: flex;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    grid-template-columns: 250px 1fr 300px;
  }
}

@media (max-width: 768px) {
  .main-content {
    grid-template-columns: 1fr;
    grid-template-rows: auto 1fr auto;
  }

  .header {
    padding: 15px 20px;
  }

  .header h2 {
    font-size: 18px;
  }
}
</style>
